﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.UserProfiles.Caching;
using Core.Interfaces.Users;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.UserProfiles.Features.Commands.Delete;

/// <summary>
/// 编辑用户偏好
/// </summary>
/// <summary>
/// 删除指定用户偏好项
/// </summary>
public class DeleteUserProfileCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 要删除的偏好项键集合（如 ["系统消息", "待办任务"]）
    /// </summary>
    public required IEnumerable<string> Keys { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => UserProfilesCacheKey.Tags;
}

public class DeleteUserProfileCommandHandler(IIdentityDbContext dbContext, ICurrentUserService currentUser)
    : IRequestHandler<DeleteUserProfileCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(DeleteUserProfileCommand request, CancellationToken cancellationToken)
    {
        var userId = currentUser.GetUserId();

        // 查询用户档案及其偏好
        var userProfile = await dbContext.UserProfiles
            .Include(x => x.Preferences)
            .FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);

        if (userProfile == null)
        {
            return await Result<bool>.FailureAsync(["配置不存在"]);
        }

        foreach (var item in request.Keys)
        {
            userProfile.ClearPreference(item);
        }

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}
